package dao.impl;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import dao.UserDao;
import pojo.User;

import javax.sql.DataSource;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Properties;

public class UserDaoImpl implements UserDao {
    @Override
    public ArrayList<User> findAll() {
        ArrayList<User> list=new ArrayList<>();
        //jdbc操作数据库的代码

        DataSource dataSource = null;
        try {
            //加载配置文件
            Properties prop=new Properties();
            prop.load(new FileInputStream("D:/code/IdeaProjects/demo0929/web/WEB-INF/lib/druid.properties"));
            //获取链接池对象
            dataSource = DruidDataSourceFactory.createDataSource(prop);
            //获取数据库链接
            Connection conn = dataSource.getConnection();

            String sql="select * from jdbc_practice;";

            //获取ps对象
            PreparedStatement ps=conn.prepareStatement(sql);

            //执行sql
            ResultSet rs = ps.executeQuery();

            while (rs.next()){
                User u=new User(rs.getString("name"), rs.getNString("id"),rs.getString("pass"));
                list.add(u);
            }

            rs.close();
            ps.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return list;

    }
}
